package cn.com.lyb.flink.window;

import cn.com.lyb.flink.bean.WaterSensor;
import cn.com.lyb.flink.split.WaterSensorMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

public class WindowReduceDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env.socketTextStream("172.32.1.6", 1234).map(new WaterSensorMapFunction());

        KeyedStream<WaterSensor, String> keyBy = sensorDS.keyBy((KeySelector<WaterSensor, String>) waterSensor -> waterSensor.getId());

        WindowedStream<WaterSensor, String, TimeWindow> window = keyBy.window(TumblingProcessingTimeWindows.of(Time.seconds(5)));
        // 增量聚合函数：来一条数据，计算一条数据； 窗口触发的时候输出计算结果
        /**
         * 窗口的reduce
         * 1. 相同key的第一条数据来的时候，不会调用reduce方法
         * 2. 增量聚合，来一条数据，就会计算一次，但是不会输出
         * 3. 在窗口触发的时候，才会输出窗口的最终计算结果
         * 4. 缺点就是输入类型和输出类型必须相同
         */
        SingleOutputStreamOperator<WaterSensor> reduce = window.reduce(new ReduceFunction<WaterSensor>() {
            @Override
            public WaterSensor reduce(WaterSensor v1, WaterSensor v2) throws Exception {
                System.out.println("调用reduce方法，v1 =" + v1 + ";v2 = " + v2);
                return new WaterSensor(v1.getId(), v2.getTs(), v1.getVc() + v2.getVc());
            }
        });
        reduce.print();
        // 全窗口函数：数据来了不计算，存起来，窗口触发的时候，计算并输出结果
        //window.process();


        env.execute();
    }
}
